package com.liuhm.controller;

import com.liuhm.VO.DataFilePreVO;
import com.liuhm.exception.BDException;
import com.liuhm.service.FileHandleService;
import com.liuhm.utils.CsvUtils;
import com.liuhm.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 上传文件类
 *
 * @author liuhaomin
 * @date 2020/6/30
 */
@Controller
@RequestMapping("/")
@Api(description = "上传文档")
public class UploadController {

    @Value("${demo.upload}")
    private String uploadPath;
    @Value("${cut.csv.line:100000}")
    private int cutCsvLine;
    @Autowired
    private FileHandleService fileHandleService;

    @GetMapping("/")
    @ApiOperation("文件上传页面")
    public String index() {
        return "index";
    }



    @PostMapping("/upload")
    @ApiOperation("文件上传")
    @ResponseBody
    public R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            throw new BDException("上传失败，请选择文件");
        }
        String originalFilename = file.getOriginalFilename().indexOf("\\") > 0 ? file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\") + 1) : file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replace("-","") + originalFilename;
        String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if(!".csv".equals(ext)){
            throw new BDException("请上传cvs文件结尾的");
        }
        File f = new File(uploadPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        File dest = new File(uploadPath + "/" + fileName);
        try {
            file.transferTo(dest);

            // 处理分割csv
            CsvUtils.dealCutCvs(dest,cutCsvLine);
            // 预览
            // 表头的位置
            int startRow=1;
            DataFilePreVO dataFilePreVO = CsvUtils.parseCsv(dest, startRow);
            // 调用生产者模式
            fileHandleService.importData(dest,startRow,dataFilePreVO.getTitleList().size(),dataFilePreVO.getTitleList());
            return R.ok();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("上传失败！");
    }
}
